/*
 * @Author: your name
 * @Date: 2021-04-03 17:26:33
 * @LastEditTime: 2021-05-11 17:04:28
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \chronic-back-end\module\authMod\controller.go
 */
package authMod

import (
	"chronic/common"
	"chronic/module/userMod"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type signInDto struct {
	Phone    string `form:"phone" json:"phone" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}

func signIn(ctx *gin.Context) {
	var input signInDto
	if err := ctx.ShouldBind(&input); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	u, err := userMod.FindUserByPhone(input.Phone)
	if err != nil {
		ctx.JSON(http.StatusConflict, gin.H{"error": err})
		return
	}
	if u.CheckPassword(input.Password) != nil {
		ctx.JSON(http.StatusOK, "账号或密码错误")
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"user": u, "token": common.GenToken(u.ID)})
}

func signInAdmin(ctx *gin.Context) {
	var input signInDto
	if err := ctx.ShouldBind(&input); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	u, err := userMod.FindAdminByPhone(input.Phone)
	if err != nil {
		ctx.JSON(http.StatusConflict, gin.H{"error": err})
		return
	}
	if u.CheckPassword(input.Password) != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "账号或密码错误"})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"user": u, "token": common.GenToken(u.ID)})
}

type signUpDto struct {
	Phone    string `form:"phone" json:"phone" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
	Role     string `form:"role" json:"role" gorm:"default:0"`
}

func signUp(ctx *gin.Context) {
	var input signUpDto
	if err := ctx.ShouldBind(&input); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	role, _ := strconv.ParseUint(input.Role, 10, 64)
	u, err := userMod.CreateUser(input.Phone, input.Password, userMod.Role(role))
	if err != nil {
		ctx.JSON(http.StatusConflict, gin.H{"error": err})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{"u": u, "token": common.GenToken(u.ID)})
}
